package com.traffic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import com.traffic.annotation.Power;
import com.traffic.constant.Const;
import com.traffic.constant.Status;

import com.traffic.entity.*;
import com.traffic.exception.BaseException;
import com.traffic.mapper.DrivedataMapper;
import com.traffic.model.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.traffic.mapper.TrajectoryMapper;
import com.traffic.service.TrajectoryService;

@Service
public class TrajectoryServiceImpl extends ServiceImpl<TrajectoryMapper, Trajectory> implements TrajectoryService{

    @Autowired
    TrajectoryMapper trajectoryMapper;
    @Autowired
    DrivedataMapper drivedataMapper;

    @Override
    public Long insertTrajectory(Map<String,Object> trajectoryParam) {

        String param[] = new String[]{"user_id","start_point","end_point","start_time","end_time","points"};

        List<String> paramList = CollUtil.newArrayList(param);
//        if (!paramList.containsAll(CollUtil.newArrayList(trajectoryParam.keySet().toArray()))) {
//            throw new BaseException(Status.PARAM_ERROR);
//        }

        Trajectory tra = new Trajectory();
        BeanUtil.copyProperties(trajectoryParam, tra, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

       //trajectoryMapper.updateById(tra);


        int result = trajectoryMapper.insert(tra);

        return tra.getId();
    }

    @Override
    public Long insertTrajectory(Long uid) {
        Trajectory tra = Trajectory.builder().userId(uid).startTime(new DateTime()).startPoint("").endPoint("").points("").build();
        tra.setUserId(uid);

        int result = trajectoryMapper.insert(tra);

        return tra.getId();
    }

    @Override
    public int updateTrajectory(Map<String, Object> trajectoryParam) {
        String param[] = new String[]{"id","user_id","start_point","end_point","start_time","end_time","points"};

        List<String> paramList = CollUtil.newArrayList(param);
//        if (!paramList.containsAll(CollUtil.newArrayList(trajectoryParam.keySet().toArray()))) {
//            throw new BaseException(Status.PARAM_ERROR);
//        }


        Trajectory tra = new Trajectory();
        BeanUtil.copyProperties(trajectoryParam, tra, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

        Trajectory old = trajectoryMapper.selectById(tra.getId());

        if(StringUtils.isNullOrEmpty(old.getStartPoint()))old.setStartPoint(tra.getStartPoint());
        old.setEndPoint(tra.getEndPoint());
        old.setStartTime(tra.getStartTime());
        old.setEndTime(tra.getEndTime());
        String oldpoints=old.getPoints();
        old.setPoints(oldpoints+tra.getPoints());

        trajectoryMapper.updateById(old);
        return 1;
    }


    /**
     * 分页查询用户的驾驶记录
     * @param userId
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Power(authority = Const.AUTH_QUERY)
    @Override
    public QueryResult queryList(Long userId, Integer currentPage, Integer pageSize) {
        IPage<Trajectory> tPage = new Page<>(currentPage, pageSize);
        QueryWrapper<Trajectory> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        // wrapper.orderByDesc("id");
        return getQueryResult(tPage, wrapper);
    }

    /**
     * 分页条件查询用户的驾驶记录
     * @param userId
     * @param currentPage
     * @param pageSize
     * @param param
     * @return
     */
    @Power(authority = Const.AUTH_QUERY)
    @Override
    public QueryResult queryList(Long userId, Integer currentPage, Integer pageSize, Map<String, Object> param) {

        /**
         * param  sTime->开始时间 eTime->结束时间
         */
        if (ObjectUtil.isNotNull(param.get("sTime")) && ObjectUtil.isNotNull(param.get("eTime"))) {
            IPage<Trajectory> tPage = new Page<>(currentPage, pageSize);

            QueryWrapper<Trajectory> wrapper = new QueryWrapper<>();

            wrapper.ge("start_time", param.get("sTime"));
            wrapper.le("start_time", param.get("eTime"));
            wrapper.eq("user_id", userId);

            return getQueryResult(tPage, wrapper);
        }else {

            IPage<Trajectory> tPage = new Page<>(currentPage, pageSize);
            QueryWrapper<Trajectory> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);
            // wrapper.orderByDesc("id");
            return getQueryResult(tPage, wrapper);
        }

    }

    /**
     * 轨迹添加批注
     * @param id
     * @param comment
     * @return
     */
    @Power(authority = Const.AUTH_ADD)
    @Override
    public Integer addComment(Long id, String comment) {
        Trajectory trajectory = trajectoryMapper.selectById(id);
        if (ObjectUtil.isNotNull(trajectory)) {
            trajectory.setComment(comment);
            trajectoryMapper.updateById(trajectory);
            return 1;
        }
        return 0;
    }

    /**
     * 抽离公用方法
     * @param tPage
     * @param wrapper
     * @return
     */
    private QueryResult getQueryResult(IPage<Trajectory> tPage, QueryWrapper<Trajectory> wrapper) {
        IPage<Trajectory> page = trajectoryMapper.selectPage(tPage, wrapper);
        Integer total = trajectoryMapper.selectCount(wrapper);

        List<Trajectory> trajectories = page.getRecords();
        List<RtDriveData> driveData = new ArrayList<>();
        trajectories.forEach(trajectory -> {
            if (ObjectUtil.isNotNull(trajectory)) {
                QueryWrapper<Drivedata> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("trail_id", trajectory.getId());
                Drivedata data = drivedataMapper.selectOne(queryWrapper);
                RtDriveData rtDriveData = RtDriveData.builder().trajectory(trajectory).drivedata(data).build();
                driveData.add(rtDriveData);
            }
        });

        QueryResult result = QueryResult.builder().data(driveData).total(total).build();
        return result;
    }

    /**
     * 获取批注
     * @param id
     * @return
     */
    @Override
    public String getComment(Long id) {
        Trajectory trajectory = trajectoryMapper.selectById(id);
        if (ObjectUtil.isNotNull(trajectory)) {
            return trajectory.getComment();
        }
        return null;
    }
}
